package kr.cafedev.hangul;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.media.MediaRecorder;
import android.os.Environment;

public class AudioRecorder {

	  final MediaRecorder recorder = new MediaRecorder();
	  final String path;
	  static final String SOUND_FORMAT = ".mp3"; 
	  boolean recording = false;

	  /**
	   * Creates a new audio recording at the given path (relative to root of SD card).
	   */
	  public AudioRecorder(String path) {
	    this.path = sanitizePath(path);
	  }
	  /*private String parseDate() {
			long time = System.currentTimeMillis();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			Date dd = new Date(time);
			return sdf.format(dd);
	 
		}*/
	  private String sanitizePath(String path) {
		  //path+= parseDate();
	    if (!path.startsWith("/")) {
	      path = "/" + path;
	    }
	    if (!path.contains(".")) {
	      path += SOUND_FORMAT;
	    }
	    return path;
	    //return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
	  }

	  /**
	   * Starts a new recording.
	   */
	  public void start() throws IOException {
		  recording = true;
	    String state = android.os.Environment.getExternalStorageState();
	    if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
	        throw new IOException("SD Card is not mounted.  It is " + state + ".");
	    }

	    // make sure the directory we plan to store the recording in exists
	    File directory = new File(path).getParentFile();
	    if (!directory.exists() && !directory.mkdirs()) {
	      throw new IOException("Path to file could not be created.");
	    }

	    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	    //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
	    recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
	    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	    recorder.setOutputFile(path);
	    recorder.prepare();
	    recorder.start();
	  }

	  /**
	   * Stops a recording that has been previously started.
	   */
	  public void stop() throws IOException {
		  recording = false;
	    recorder.stop();
	    recorder.release();
	  }
	  public String getPath(){
		  return path;
	  }
	  public boolean isRecording(){
		  return recording;
	  }

	}
